package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.api.services.PermissionApiService;
import com.molichuxing.gateway.bff.permission.entity.request.*;
import com.molichuxing.gateway.bff.permission.entity.response.*;
import com.molichuxing.gateway.bff.permission.services.*;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.infrastructure.dto.response.response.ResourceDto;
import com.molichuxing.services.property.SystemTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @Author: renzhengyu
 * @Description:
 * @Date: Created in 10:39 2019/9/9
 * @Modified By:
 **/
@Api(tags = "账户权限相关接口")
@RestController
@RequestMapping(value = "/permission")
public class PermissionApiServiceImpl extends RootApiService implements PermissionApiService {
    private static final Logger logger = LoggerFactory.getLogger(PermissionApiServiceImpl.class);

    @Resource
    private AccountBffService accountBffService;

    @Resource
    private OperationLogBffService operationLogBffService;

    @Resource
    private LoginLogBffService loginLogBffService;

    @Resource
    private GroupBffService groupBffService;

    @Resource
    private ResourceBffService resourceBffService;

    /**
     * 账户登录
     *
     * @param params
     * @return
     */
    @Override
    @ApiOperation(value = "账户登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String")})
    @PostMapping(value = "login")
    public ResponseResult<AccountLoginVo> login(@RequestBody Map<String, Object> params) {
        ResponseResult<AccountLoginVo> result = new ResponseResult<>();
        try {
            params.put("systemType", SystemTypeEnum.DEALER);
            result.success(accountBffService.login(params));
        } catch (BizException e) {
            logger.error("[login]登录异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[login]登录异常:", e);
            result.error("登录异常");
        }

        return result;
    }

    /**
     * 账户登出
     *
     * @return
     */
    @ApiOperation(value = "账户登出")
    @PostMapping(value = "/logOut")
    @Override
    public ResponseResult<Boolean> logOut() {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        try {
            accountBffService.logOut();
            return result.success("成功", Boolean.TRUE);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("失败", Boolean.FALSE);
    }

    @Override
    @ApiOperation(value = "获取操作日志列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountId", value = "用户id", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "operationStartDate", value = "开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "operationEndDate", value = "结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

    })
    @GetMapping(value = "/operation/log/list")
    public ResponseResult<Paged<OperationLogVo>> getOperationLogByDealerId(@RequestParam(required = false) Map<String, Object> map,
                                                                           @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize) {
        ResponseResult<Paged<OperationLogVo>> result = new ResponseResult<>();
        try {
            //获取当前登录的经销商id
            Integer dealerId = RequestAttrUtil.getCurrentDealerId();
            map.put("dealerId", dealerId);
            result.success(operationLogBffService.getOperationLogByDealerId(map, pageNum, pageSize));
        } catch (BizException e) {
            logger.error("[list]获取操作信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[list]获取操作列表信息异常", e);
            result.error("获取操作列表信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取登陆日志列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountName", value = "用户名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "operationStartDate", value = "开始时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "operationEndDate", value = "结束时间", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

    })
    @GetMapping(value = "/login/log/list")
    public ResponseResult<Paged<LoginLogVo>> getLoginLogByDealerId(@RequestParam(required = false) Map<String, Object> map,
                                                                   @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize) {
        ResponseResult<Paged<LoginLogVo>> result = new ResponseResult<>();
        try {
            //获取当前登录的经销商id
            Integer dealerId = RequestAttrUtil.getCurrentDealerId();
            map.put("dealerId", dealerId);
            result.success(loginLogBffService.getLoginLogByDealerId(map, pageNum, pageSize));
        } catch (BizException e) {
            logger.error("[list]获取操作信息异常", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[list]获取操作列表信息异常", e);
            result.error("获取登陆列表信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "获取后台用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realName", value = "真实姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "账号状态（0：启用， 1：禁用）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "一页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/account/getAccountList")
    public ResponseResult<Paged<AccountVo>> getAccount(@RequestParam Map<String, Object> params, @RequestParam int pageNum, @RequestParam int pageSize) {
        ResponseResult<Paged<AccountVo>> result = new ResponseResult();
        try {
            params.put("dealerId", RequestAttrUtil.getCurrentDealerId());
            return result.success(accountBffService.getAccountList(params, pageNum, pageSize));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("获取失败");
    }

    @Override
    @ApiOperation(value = "添加用户")
    @PostMapping(value = "/account/createAccount")
    public ResponseResult<Boolean> createAccount(@RequestBody @Valid AccountCreateVo vo) {
        return accountBffService.createAccount(vo);
    }

    @Override
    @ApiOperation(value = "修改用户")
    @PostMapping(value = "/account/modifyAccount")
    public ResponseResult<Boolean> modifyAccount(@RequestBody @Valid AccountModifyVo vo) {
        return accountBffService.modifyAccount(vo);
    }

    @ApiOperation(value = "重置密码")
    @PostMapping(value = "/account/modifyResetPassword")
    public ResponseResult<Boolean> modifyResetPassword(@RequestBody AccountModifyVo vo) {
        return accountBffService.modifyResetPassword(vo);
    }

    @Override
    @ApiOperation(value = "用户修改页获取角色")
    @GetMapping(value = "/account/getGroupListInModifyAccountPage")
    public ResponseResult<List<GroupVo>> getGroupListInModifyAccountPage() {

        ResponseResult<List<GroupVo>> result = new ResponseResult<>();

        try {
            return result.success("查询成功", groupBffService.getGroupListInModifyAccountPage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("查询失败");
    }

    @Override
    @ApiOperation(value = "获取角色列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "角色名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "status", value = "角色状态（0：启用， 1：禁用）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "一页显示条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/group/getGroupList")
    public ResponseResult<Paged<GroupVo>> getGroupList(@RequestParam Map<String, Object> param, @RequestParam int pageNum, @RequestParam int pageSize) {
        ResponseResult<Paged<GroupVo>> result = new ResponseResult<>();
        try {
            return groupBffService.getGroupList(param, pageNum, pageSize);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("获取失败");
    }

    @Override
    @ApiOperation(value = "添加角色")
    @PostMapping(value = "/group/createGroup")
    public ResponseResult<Boolean> createGroup(@RequestBody GroupCreateVo vo) {
        return groupBffService.createGroup(vo);
    }

    @Override
    @ApiOperation(value = "修改角色")
    @PostMapping(value = "/group/modifyGroup")
    public ResponseResult<Boolean> modifyGroup(@RequestBody GroupModifyVo vo) {
        return groupBffService.modifyGroup(vo);
    }

    @Override
    @ApiOperation(value = "角色配置页获取权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "角色id", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/group/getPermissionTree")
    public ResponseResult<GroupBindResourceVo> getPermissionTree(@RequestParam int groupId) {
        ResponseResult<GroupBindResourceVo> result = new ResponseResult();

        try {
            return result.success("获取成功", groupBffService.getPermissionTree(groupId));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("获取失败");
    }

    @Override
    @ApiOperation(value = "为角色绑定权限")
    @PostMapping(value = "/group/createBatchGroupResource")
    public ResponseResult<Boolean> createBatchGroupResource(@RequestBody(required = true) GroupBindVo vo) {
        ResponseResult<Boolean> result = new ResponseResult<Boolean>();
        if (vo.getGroupId() <= 0)
            return result.error("角色id不能为空");
        try {
            return groupBffService.createBatchGroupResource(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("失败", Boolean.FALSE);
    }

    /**
     * 获得op左侧菜单树
     *
     * @return
     */
    @Override
    @ApiOperation(value = "获取左侧菜单树")
    @PostMapping(value = "/getMenuList")
    public ResponseResult<List<ResourceDto>> getMenuList() {
        ResponseResult<List<ResourceDto>> result = new ResponseResult<List<ResourceDto>>();
        try {
            List<ResourceDto> menuTree = resourceBffService.getMenuTree();
            return result.success("成功", menuTree);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result.error("失败");
    }

    @Override
    @ApiOperation(value = "修改密码")
    @PostMapping(value = "/account/modifyPassword")
    public ResponseResult<Boolean> modifyPassword(@RequestBody ModifyPassowrdVo vo) {
        try {
            return accountBffService.modifyPassword(vo);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new ResponseResult<Boolean>().error("失败", Boolean.FALSE);
    }
}
